package com.zjdiepu.www.proxy.task;

import java.io.File;
import java.net.URL;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import com.diepu.www.client.partner.proxy.request.UpdateDownloadStatusRequest;
import com.diepu.www.client.partner.proxy.response.DiepuYwInterviewInfo;
import com.diepu.www.client.partner.proxy.response.SynInterviewInfoResponse;
import com.zjdiepu.www.base.enums.status.DownloadStatus;
import com.zjdiepu.www.base.enums.status.PushStatus;
import com.zjdiepu.www.common.consts.ThreadFactory;
import com.zjdiepu.www.common.util.DateUtil;
import com.zjdiepu.www.config.FileProxyConfig;
import com.zjdiepu.www.enums.TransferModeID;
import com.zjdiepu.www.hzicbc.biz.IHzicbcProxyService;
import com.zjdiepu.www.proxy.dao.transfer.TransferYwInterviewInfoMapper;
import com.zjdiepu.www.proxy.model.dto.transfer.TransferYwInterviewInfo;
import com.zjdiepu.www.request.BaseRequest;
import com.zjdiepu.www.security.exception.BasePartnerException;
import com.zjdiepu.www.service.partner.IDiepuService;




/**
 * 同步面签信息
 * @author Administrator
 *
 */
@Component
public class SynInterviewInfoTask {
	private final Logger logger = LoggerFactory.getLogger(getClass());
	@Resource
	private IDiepuService diepuService;
	@Resource
	private IHzicbcProxyService hzicbcProxyService;
	@Resource
	private TransferYwInterviewInfoMapper transferYwInterviewInfoMapper;
	@Resource
	private FileProxyConfig fileProxyConfig;
	/**
	 * 同步面签信息
	 */
	@Scheduled(fixedRateString = "${schedule.syn.interview.info}")
	private void synInterviewInfo() {
		try {
			BaseRequest request = new BaseRequest();
			SynInterviewInfoResponse synInterviewInfo = diepuService.synInterviewInfo(request);
			if(null != synInterviewInfo) {
				List<DiepuYwInterviewInfo> interviewInfos = synInterviewInfo.getInterviewInfos();
				if(CollectionUtils.isNotEmpty(interviewInfos)) {
					//目录
					String dataFormat = DateUtil.dateTo8Str(new Date());
					String filePath = fileProxyConfig.getMianqianRonglianYun() + dataFormat + "/";  //数据库地址
					File folder = new File(fileProxyConfig.getBasePathNginx() + filePath);//保存地址
					if(!folder.exists()) {
						folder.mkdirs();
					}
					for(DiepuYwInterviewInfo interviewInfo : interviewInfos) {
						String id = interviewInfo.getId();
						if(StringUtils.isBlank(id)){
							logger.error("同步过来的面签信息有记录唯一标识为空.");
							continue;
						}
						
						
						ThreadFactory.THREAD_SERVICE.submit(() -> {
							TransferYwInterviewInfo dbTransferYwInterviewInfo = transferYwInterviewInfoMapper.selectByPrimaryKey(id);
							//判断是否为新的记录
							boolean insert = false;
							if(null == dbTransferYwInterviewInfo) {
								insert = true;
								dbTransferYwInterviewInfo = new TransferYwInterviewInfo();
							}
							
							//判断是否需要重新下载
							boolean needDownload = false;
							String urlQiniu = interviewInfo.getUrlQiniu(); //为空的不会推送过来,不需要再验证
							String dbUrlQiniu = dbTransferYwInterviewInfo.getUrlQiniu(); //数据库远程路径
							String dbUrlLocal = dbTransferYwInterviewInfo.getUrlLocal();
							Integer dbDownloadStatus = dbTransferYwInterviewInfo.getDownloadStatus();
							String fileName = urlQiniu.substring(urlQiniu.lastIndexOf("/") + 1);
							String urlLocal = filePath + fileName;
							if(!urlQiniu.equals(dbUrlQiniu)) {
								needDownload = true;
							}
							//文件丢失也要重新下载
							File dbLocalFile = new File(fileProxyConfig.getBasePathNginx() + dbUrlLocal);
							if(!dbLocalFile.exists()) {
								needDownload = true;
							}
							//先拷贝数据，再维护数据
							BeanUtils.copyProperties(interviewInfo, dbTransferYwInterviewInfo); 
							//需要重新下载，保存本地路径
							if(needDownload) { 
								dbTransferYwInterviewInfo.setUrlLocal(urlLocal);
								dbTransferYwInterviewInfo.setUrlQiniu(urlQiniu);
								dbTransferYwInterviewInfo.setDownloadStatus(DownloadStatus.WEI_XIA_ZAI.getCode());
								Integer pushStatus = dbTransferYwInterviewInfo.getPushStatus();
								if(PushStatus.YI_TUI_SONG.getCode().equals(pushStatus)) {
									dbTransferYwInterviewInfo.setPushStatus(PushStatus.WEI_TUI_SONG.getCode());
								}
							} else { //不需要下载，保留原状态
								dbTransferYwInterviewInfo.setUrlLocal(null);
								dbTransferYwInterviewInfo.setUrlQiniu(null);
								dbTransferYwInterviewInfo.setPushStatus(null);
								dbTransferYwInterviewInfo.setDownloadStatus(null);
							}
							
							if(insert) {
								dbTransferYwInterviewInfo.initInsertData(TransferModeID.TONG_BU_MIAN_QIAN_SHU_JU.getCode(), TransferModeID.TONG_BU_MIAN_QIAN_SHU_JU.getValue());
							} else {
								dbTransferYwInterviewInfo.initUpdateData(TransferModeID.TONG_BU_MIAN_QIAN_SHU_JU.getCode(), TransferModeID.TONG_BU_MIAN_QIAN_SHU_JU.getValue());
							}
							dbTransferYwInterviewInfo.setId(id);//还原ID
							
							//判断下载是否成功
							boolean downloadSuccess = false;
							if(needDownload) {
								try {
									File localFile = new File(fileProxyConfig.getBasePathNginx() + urlLocal);
									FileUtils.copyURLToFile(new URL(urlQiniu), localFile);
									downloadSuccess = true;
								} catch (Exception e) {
									logger.error("拷贝远程路径文件到本地失败。业务ID：{}，路径：{}。",dbTransferYwInterviewInfo.getBusiId(), urlQiniu, e);
								}
							} else {
								downloadSuccess = true;
							}
							
							if(downloadSuccess) { //下载成功
								boolean pushDownloadStatus = true;
								try {
									if(!DownloadStatus.YI_XIA_ZAI.getCode().equals(dbDownloadStatus)) {
										UpdateDownloadStatusRequest updateDownloadStatusRequest = new UpdateDownloadStatusRequest();
										updateDownloadStatusRequest.setBusiId(interviewInfo.getBusiId());
										updateDownloadStatusRequest.setDownloadStatus(DownloadStatus.YI_XIA_ZAI.getCode());
										updateDownloadStatusRequest.setUrlLocal(urlLocal);
										pushDownloadStatus = diepuService.downloadStatus(updateDownloadStatusRequest);
									}
									if(pushDownloadStatus) {
										dbTransferYwInterviewInfo.setDownloadStatus(DownloadStatus.YI_XIA_ZAI.getCode()); //推送成功后才更新已下载
									} else {
										dbTransferYwInterviewInfo.setDownloadStatus(DownloadStatus.WEI_XIA_ZAI.getCode());
									}
								} catch (Exception e) {
									logger.error("下载附件成功，但推送下载状态到主程序异常。业务ID：{}。",dbTransferYwInterviewInfo.getBusiId(), e);
								}
							}
							
							if(insert) {
								transferYwInterviewInfoMapper.insert(dbTransferYwInterviewInfo);
							} else {
								transferYwInterviewInfoMapper.updateByPrimaryKeySelective(dbTransferYwInterviewInfo);
							}
						});
					}
				}
			}
		} catch (BasePartnerException e) {
			logger.error("同步主程序未推送面签信息失败。", e);
		}
	}
}
